package no.weather;

import java.text.SimpleDateFormat;
import java.util.List;

import no.weather.weatherProvider.GetWeatherNowAsync;
import no.weather.weatherProvider.StationIsDeletedException;
import no.weather.weatherProvider.WeatherDatabase;
import no.weather.weatherProvider.WeatherProvider;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class WeatherReportView extends ListActivity {
	private final static int ADD_FAVORITE = Menu.FIRST;
	private final static int GET_CUSTOM_TIME = Menu.FIRST + 1;
	private WeatherStation mStation;
	private List<WeatherElement> mWeather;
	private WeatherProvider provider;
	private Integer setHour = null, setDay = null, setMonth = null,
			setYear = null;

	private void addToFavorite() {
		provider.addFavorite(mStation.getId(), mStation.getProvider());
	}

	private void getWeather() {
		try {
			
			mWeather = provider.getWeatherNow(mStation,null,3600*24);
		} catch (StationIsDeletedException e) {
			stationIsDeleted();
		}
		writeWeather();

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weatherreport);
		provider = new WeatherProvider(this);

		Bundle extra = getIntent().getExtras();
		String stationId = extra.getString(WeatherDatabase.STATION_ID);
		String stationProvider = extra
				.getString(WeatherDatabase.STATION_PROVIDER);

		setResult(RESULT_OK);
		WeatherStation station = null;
		try {
			station = provider.getStation(stationId, stationProvider, true);
		} catch (StationIsDeletedException e) {
			stationIsDeleted();
		}
		mStation = station;

		TextView stationName = (TextView) findViewById(R.id.weatherrepport_header_station_name);
		stationName.setText(station.getName());

		((TextView) findViewById(R.id.weatherrepport_header_provider))
				.setText(station.getProvider());
		((TextView) findViewById(R.id.weatherrepport_header_altitude))
				.setText(station.getLocation().getAltitude() + " m.");
		getWeather();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		if (mStation.getIsFavorite()) {
			menu.add(0, ADD_FAVORITE, 0, R.string.Remove_favorite);

		} else {
			menu.add(0, ADD_FAVORITE, 0, R.string.Add_favorite);

		}
		menu.add(0, GET_CUSTOM_TIME, Menu.NONE, R.string.Select_time_and_day);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case ADD_FAVORITE:
			if (!mStation.getIsFavorite()) {
				addToFavorite();
				mStation.setIsFavorite(true);
				item.setTitle(R.string.Remove_favorite);
			} else {
				removeFromFavorite();
				mStation.setIsFavorite(false);
				item.setTitle(R.string.Add_favorite);
			}
			return true;
		case GET_CUSTOM_TIME:
			openSetCumstomTime();
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private void openSetCumstomTime() {
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.get_time_and_date_dialog, null);
		final DatePicker datePicker = (DatePicker) layout
				.findViewById(R.id.get_time_datepicker);

		final TimePicker timePicker = (TimePicker) layout
				.findViewById(R.id.get_time_timepicker);
		timePicker.setIs24HourView(true);
		if (setHour != null) {
			datePicker.updateDate(setYear, setMonth, setDay);
			timePicker.setCurrentHour(setHour);
		}

		Builder builder = new AlertDialog.Builder(this);
		builder.setView(layout);
		builder.setPositiveButton("OK", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Integer hour = timePicker.getCurrentHour();
				Integer day = datePicker.getDayOfMonth();
				Integer month = datePicker.getMonth();
				Integer year = datePicker.getYear();
				dialog.cancel();
				showWeather(year, month, day, hour);
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();

	}

	private void removeFromFavorite() {
		provider.deleteFavorite(mStation.getId(), mStation.getProvider());
	}

	private void showDescription(int position) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mWeather.get(position).getType().getDescription())
				.setCancelable(false)
				.setPositiveButton(getResources().getString(R.string.Close),
						new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		AlertDialog info = builder.create();
		info.show();
	}

	protected void showWeather(Integer year, Integer month, Integer day,
			Integer hour) {
		setYear = year;
		setMonth = month;
		setDay = day;
		setHour = hour;
		try {
			mWeather = provider.getWeather(mStation, year, month, day, hour);
		} catch (StationIsDeletedException e) {
			stationIsDeleted();
		}
		writeWeather();
	}

	/**
	 * 
	 */
	private void stationIsDeleted() {
		Toast toast = Toast.makeText(getApplicationContext(),
				R.string.StationIsDeleted, Toast.LENGTH_LONG);
		toast.show();
		setResult(RESULT_CANCELED);
		finish();
	}

	private void writeWeather() {
		if (mWeather == null)
			return;
		ListWeatherElementAdapter adapter = new ListWeatherElementAdapter(
				mWeather);
		setListAdapter(adapter);
		ListView lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				showDescription(position);
			}
		});

		if (mWeather.size() > 0 && mWeather.get(0).getFrom() != null) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			TextView time = (TextView) findViewById(R.id.weatherrepport_header_time);
			time.setText(df.format(mWeather.get(0).getFrom()));
		}
		TextView emptyView = (TextView) lv.getEmptyView();
		emptyView.setText(R.string.No_date);
	}

	private class ListWeatherElementAdapter implements ListAdapter {
		private LayoutInflater mInflater;
		private List<WeatherElement> mWeather;

		public ListWeatherElementAdapter(List<WeatherElement> elements) {
			super();
			mWeather = elements;
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public boolean areAllItemsEnabled() {
			return true;
		}

		@Override
		public int getCount() {
			return mWeather.size();
		}

		@Override
		public Object getItem(int position) {
			return mWeather.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getItemViewType(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.weather_report_item,
						null);
			}

			WeatherElement element = mWeather.get(position);
			TextView descriptionView = (TextView) convertView
					.findViewById(R.id.weather_report_item_description);
			String description = element.getType().getName();
			descriptionView.setText(description);

			TextView valueView = (TextView) convertView
					.findViewById(R.id.weather_report_item_value);
			String value = element.getValue() + element.getType().getUnit();
			valueView.setText(value);

			return convertView;
		}

		@Override
		public int getViewTypeCount() {
			return 1;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public boolean isEmpty() {
			return mWeather.isEmpty();
		}

		@Override
		public boolean isEnabled(int position) {
			return true;
		}

		@Override
		public void registerDataSetObserver(DataSetObserver observer) {
			// TODO Auto-generated method stub

		}

		@Override
		public void unregisterDataSetObserver(DataSetObserver observer) {
			// TODO Auto-generated method stub

		}

	}
	
	
	private class SetWeatherNowAsync extends GetWeatherNowAsync {
		public SetWeatherNowAsync() {
			super(getApplicationContext());
		}
		
		@Override
		protected void onProgressUpdate(Float... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}
}
